package com.example.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.file.Path;
import java.nio.file.Paths;

@Configuration
public class StaticResourceConfig implements WebMvcConfigurer {

    @Autowired
    private FileStorageConfig fileStorageConfig;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 获取上传目录的绝对路径
        Path uploadDir = Paths.get(fileStorageConfig.getUploadDir()).toAbsolutePath().normalize();

        // 配置头像资源映射
        registry.addResourceHandler("/users/avatars/**")
                .addResourceLocations("file:" + uploadDir.toString() + "/avatars/")
                .setCachePeriod(3600)
                .resourceChain(true);

        // 配置其他上传文件的映射
        registry.addResourceHandler("/uploads/**")
                .addResourceLocations("file:" + uploadDir.toString() + "/")
                .setCachePeriod(3600)
                .resourceChain(true);

        // 添加公告附件资源映射
        registry.addResourceHandler("/uploads/announcements/**")
                .addResourceLocations("file:" + uploadDir.toString() + "/announcements/")
                .setCachePeriod(3600)
                .resourceChain(true);

        // 添加默认头像资源
        registry.addResourceHandler("/default-avatar/**")
                .addResourceLocations("classpath:/static/images/")
                .setCachePeriod(3600);
    }
}